
local redis = require 'redis';
local host = "127.0.0.1"
local port = 6379

client = redis.connect(host, port)

redis.call = function(cmd, ...)
    --return assert(loadstring('return client:'.. string.lower(cmd) ..'(...)'))(...)
    return assert(load('return client:'.. string.lower(cmd) ..'(...)'))(...)
end

local KEYS = {"liveshowcenter:billboard:COMMON_ACTOR:zset"};
local ARGV = {"cuihua", 1};



--[[
    获取某个用户在榜单中的信息

    key[1]: 排行榜的key
    ARGV[1]: 要查询的用户id
    ARGV[2]: 排行榜的长度

    返回数组参数
        ret[0] : 当前排名，从1开始，如果当期集合中没有该用户，返回-1
        ret[1]: 与第一名的分数差距
        ret[2]: 与榜单最后一名的差距
        ret[3]: 与前一名的分数差距(用户需要在集合中)

]]

local redisKey = KEYS[1];
local userId = ARGV[1];
local boardLength = ARGV[2];

-- 自己的分数
local currentUserScore = redis.call('zscore', redisKey, userId);
if(type(currentUserScore) == "nil")then
    currentUserScore = 0.0;
end

-- 2维数组
local boardLastTable = redis.call('ZREVRANGE', redisKey, boardLength -1, boardLength -1, 'WITHSCORES');
-- 榜单最后一名的分数
local boardLastScore;
if(type(boardLastTable[1]) == "nil" or type(boardLastTable[1][2]) == "nil")then
    boardLastScore = 0.0;
else
    boardLastScore = boardLastTable[1][2];
end


--榜单第一名的分数
local top1Table = redis.call('ZREVRANGE', redisKey, 0, 0, 'WITHSCORES');
local top1Score ;
if(type(top1Table[1]) == "nil" or type(top1Table[1][2]) == "nil")then
    top1Score = 0.0;
else
    top1Score = top1Table[1][2];
end

-- 和排行榜最后一名的差距
local gapWithBoardLast = boardLastScore - currentUserScore;

-- 和第一名的差距
local gapWithTop1 = top1Score - currentUserScore;

-- 当前排名，从1开始
local currentUserRank = redis.call('ZREVRANK', redisKey, userId);
if(type(currentUserRank) == "nil")then
    currentUserRank = -2;
end

-- 和前一名的差距
local gapWithPrevious;
if(currentUserRank <= 0)then
    --没有排名
    gapWithPrevious = 0.0;
else
    --前一名的分数
    local previousTable = redis.call('ZREVRANGE', redisKey, currentUserRank -1, currentUserRank -1, 'WITHSCORES');
    local previousScore = previousTable[1][2];
    gapWithPrevious = previousScore - currentUserScore;
end

return { currentUserRank + 1, gapWithTop1, gapWithBoardLast, gapWithPrevious};
